<?php
namespace app\common\controller;

class Selfmcrypt
{
    //两位字符必须小于字符串总长度
    private $first_index = 0;
    private $second_index = 0;
    private $string_length = 0;

    public function __construct($length=8,$fi_index=1,$se_index=5)
    {
        $this->string_length = $length;
        $this->second_index = $length < $se_index?$length:$se_index;
        $this->first_index = $se_index < $fi_index?$se_index:$fi_index;
    }

    //加密 string定长为8位 取字符串的两位字符拼接到字符前用于加密规则
    public function encode($string='')
    {
        if(empty($string)) return "加密字符串为空";
        //if(strlen($string)!=$this->string_length) return "字符串长度只能是".$this->string_length."位";
        $string = $string[$this->first_index].$string[$this->second_index].$string;
        //base64加密
        $encodestring = base64_encode($string);
        $encodestring = urlencode($encodestring);
        return $encodestring;
    }
    //解密
    public function decode($encodestring)
    {
        //防止路由转义
        $decodestring = urldecode($encodestring);
        //base64解密
        $decodestring = base64_decode($decodestring);
        //取字符的相应位数进行比对
        $first = substr($decodestring,0,1);
        $second = substr($decodestring,1,1);
        $string = substr($decodestring,2);
        $_first = $string[$this->first_index];
        $_second = $string[$this->second_index];
        if($first == $_first && $second == $_second){
            return $string;//验证通过
        }else{
            return "鉴权失败";
        }
    }
}